#!/bin/bash
set -e

### 配置参数 ###
MASTER_IP="192.168.64.10"   # 请改成你的 Master 节点 IP
POD_NET_CIDR="192.168.0.0/16"
IMAGE_REPO="registry.aliyuncs.com/google_containers"
K8S_VERSION="v1.29"         # 稳定版

echo "[INFO] 更新系统并安装基础工具..."
sudo apt-get update -y
sudo apt-get upgrade -y
sudo apt-get install -y apt-transport-https ca-certificates curl gpg wget gnupg lsb-release

echo "[INFO] 关闭 swap..."
sudo swapoff -a
sudo sed -i '/ swap / s/^/#/' /etc/fstab

echo "[INFO] 加载内核模块..."
cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
overlay
br_netfilter
EOF
sudo modprobe overlay
sudo modprobe br_netfilter

echo "[INFO] 配置 sysctl 网络参数..."
cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables  = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward                 = 1
EOF
sudo sysctl --system

echo "[INFO] 安装 containerd..."
sudo apt-get install -y containerd
sudo mkdir -p /etc/containerd
sudo containerd config default | sudo tee /etc/containerd/config.toml
sudo sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml
sudo systemctl restart containerd
sudo systemctl enable containerd

echo "[INFO] 添加 Kubernetes 源..."
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://pkgs.k8s.io/core:/stable:/${K8S_VERSION}/deb/Release.key | \
  sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg

echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] \
https://pkgs.k8s.io/core:/stable:/${K8S_VERSION}/deb/ /" | \
  sudo tee /etc/apt/sources.list.d/kubernetes.list

sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl

echo "[INFO] 预拉取国内镜像..."
sudo kubeadm config images pull --image-repository ${IMAGE_REPO}

HOSTNAME=$(hostname)
if [[ "$HOSTNAME" == "k8s-master" ]]; then
    echo "[INFO] 初始化 Master 节点..."
    sudo kubeadm reset -f
    sudo kubeadm init \
      --apiserver-advertise-address=${MASTER_IP} \
      --pod-network-cidr=${POD_NET_CIDR} \
      --image-repository ${IMAGE_REPO}

    echo "[INFO] 配置 kubectl..."
    mkdir -p $HOME/.kube
    sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
    sudo chown $(id -u):$(id -g) $HOME/.kube/config

    echo "[INFO] 安装 Calico 网络插件..."
    kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.27.3/manifests/calico.yaml

    echo "[INFO] Master 节点初始化完成!"
    echo "等待 pods 网络插件启动后再让 worker 节点加入集群."
    echo "使用以下命令查看初始化状态:"
    echo "kubectl get nodes && kubectl get pods -n kube-system"

else
    echo "[INFO] 请到 Master 节点运行下面命令获取 join token:"
    echo "  kubeadm token create --print-join-command"
    echo "[INFO] 然后在本节点执行该 join 命令即可加入集群."
fi
